package com.aboo.redis.action;

import com.aboo.frame.util.redis.DistributedLockUtil;
import com.aboo.frame.vo.ReturnVO;
import com.aboo.redis.domain.po.Cell;
import com.aboo.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/redis")
public class RedisAction {

    @Resource
    private RedisService redisService;
    @Resource
    private DistributedLockUtil distributedLockUtil;

    @RequestMapping("/getSetRedisStr")
    public ReturnVO<Object> getSetRedisStr(HttpServletRequest request) {
        ReturnVO<Object> rv = new ReturnVO<>();
        String data = redisService.getSetRedisStr();

        log.info("String in Redis: {}", (data == null ? "null" : data));
        rv.setData(data);
        return rv;
    }

    @RequestMapping("/getSetRedisObj")
    public ReturnVO<Cell> getSetRedisObj(HttpServletRequest request) {
        ReturnVO<Cell> rv = new ReturnVO<>();
        Cell data = redisService.getSetRedisObj();

        log.info("Object in Redis: {}", (data == null ? "null" : data.toString()));
        rv.setData(data);
        return rv;
    }

    @RequestMapping("/incrRedis")
    public ReturnVO<Object> incrRedis(HttpServletRequest request) {
        ReturnVO<Object> rv = new ReturnVO<>();
        String data = redisService.incrRedis();

        log.info(data);
        rv.setData(data);
        return rv;
    }

    @RequestMapping("/scoreRedis")
    public ReturnVO<Object> scoreRedis(HttpServletRequest request) {
        ReturnVO<Object> rv = new ReturnVO<>();
        String data = redisService.scoreRedis();

        log.info(data);
        rv.setData(data);
        return rv;
    }

    @PostMapping("/distributedLock")
    public ReturnVO<Object> distributedLock() {
        String key = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
        boolean rt1 = distributedLockUtil.tryGetDistributedLock(key, "845", 1);
        boolean rt2 = distributedLockUtil.tryGetDistributedLock(key, "846", 1);
        boolean rt3 = distributedLockUtil.tryGetDistributedLock(key, "847", 1);
        boolean rt4 = distributedLockUtil.releaseDistributedLock(key, "845");
        boolean rt5 = distributedLockUtil.releaseDistributedLock(key, "846");
        boolean rt6 = distributedLockUtil.releaseDistributedLock(key, "847");
        boolean rt7 = distributedLockUtil.tryGetDistributedLock(key, "848", 1);
        boolean rt8 = distributedLockUtil.releaseDistributedLock(key, "848");
        log.info("rt1:{}, rt2:{}，rt3:{}, rt4:{}，rt5:{}, rt6:{}，rt7:{}, rt8:{}", rt1, rt2, rt3, rt4, rt5, rt6, rt7, rt8);
        return new ReturnVO<>();
    }

}
